package team.bluepen.supermarket.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.io.Closeable;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author RollW
 */
public class KafkaReceiver<T> implements Closeable {
    private static final Deserializer<String> STRING_DESERIALIZER = new StringDeserializer();
    private final String topic;
    private final String key;
    private final KafkaConsumer<String, String> consumer;
    private final KafkaDeserializer<T> deserializer;
    private final KafkaReceiveCallback<T> callback;

    public KafkaReceiver(String topic, String servers, String group, String key,
                         KafkaDeserializer<T> deserializer,
                         KafkaReceiveCallback<T> callback) {
        this.deserializer = deserializer;
        this.callback = callback;
        this.key = key;
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, group);
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        this.consumer = new KafkaConsumer<>(
                properties,
                STRING_DESERIALIZER,
                STRING_DESERIALIZER);
        this.topic = topic;
        consumer.subscribe(Collections.singletonList(topic));

        resetFromBeginning();
    }

    public KafkaReceiver(String topic, String servers,
                         KafkaDeserializer<T> deserializer,
                         KafkaReceiveCallback<T> callback) {
        this(topic, servers, "ConsumerG1", null, deserializer, callback);
    }

    private void resetFromBeginning() {
        consumer.poll(Duration.ofSeconds(1));
        Set<TopicPartition> topicPartitions = consumer.assignment();
        consumer.seekToBeginning(topicPartitions);
    }


    private final ScheduledExecutorService scheduledExecutorService =
            Executors.newSingleThreadScheduledExecutor();

    public void start() {
        scheduledExecutorService.scheduleAtFixedRate(
                this::consumeProductMessage,
                0,
                4,
                TimeUnit.SECONDS);
    }

    public void stop() {
        scheduledExecutorService.shutdown();
        consumer.close();
    }

    public String getTopic() {
        return topic;
    }

    private void consumeProductMessage() {
        ConsumerRecords<String, String> records =
                consumer.poll(Duration.of(10, ChronoUnit.SECONDS));
        for (ConsumerRecord<String, String> record : records) {
            if (key == null) {
                call(record);
                continue;
            }
            if (!Objects.equals(record.key(), key)) {
                continue;
            }
            call(record);
        }
    }

    private void call(ConsumerRecord<String, String> record) {
        final String deValue = record.value();
        T data = deserializer.deserialize(deValue);
        callback.onReceive(data);
    }

    @Override
    public void close() {
        stop();
    }
}
